#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>

int last_code = 0;
#define LINE_SIZE 1024
#define ARGC_SIZE 32
char commandline[LINE_SIZE];
char* _argv[ARGC_SIZE];
char pwd[LINE_SIZE];
char myenv[LINE_SIZE];

#define NONE -1
int rdir = NONE;
char* filename = NULL;
#define IN_RDIR 0
#define OUT_RDIR 1
#define APPEND_RDIR 2

void check_rdir(char* cmd)
{
    char* pos = cmd;
    while(*pos)
    {
        if(*pos == '>')
        {
            *pos = '\0';
            ++pos;
            if(*pos == '>')
            {
                *pos = '\0';
                rdir = APPEND_RDIR;
                ++pos;
                while(isspace(*pos))
                {
                    ++pos;
                }
                filename = pos;
                
            }
            else 
            {
                rdir = OUT_RDIR;

                while(isspace(*pos))
                {
                    pos++;
                }
                filename = pos;
            }

            break;

        }
        else if(*pos == '<')
        {
            *pos = '\0';
            rdir = IN_RDIR;
            ++pos;
            while(isspace(*pos))
            {
                ++pos;
            }
            filename = pos;
            
            break;
        }
        pos++;
    }



}

void interact(char* cline, int size)
{
    
        printf("[%s@%s %s]#", getenv("USER"), getenv("HOSTNAME"),getenv("PWD"));
        fgets(cline, size, stdin);
        cline[strlen(cline) - 1] = '\0';

        check_rdir(cline);
}

int splitstring()
{
        int i = 0;
        _argv[i++] = strtok(commandline, " ");
        while(_argv[i++] = strtok(NULL, " "));
        
        return i - 1;

}

void getpwd()
{
    getcwd(pwd, sizeof(pwd));
}

void normalExecute()
{
    pid_t id = fork();
    if(id == 0)
    {
        int fd = 0;
        if(rdir == IN_RDIR)
        {
           fd = open(filename, O_RDONLY);
           dup2(fd, 0);
        }
        else if(rdir == OUT_RDIR)
        {
            fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0666);
            dup2(fd, 1);
        }
        else if(rdir == APPEND_RDIR)
        {
            fd = open(filename, O_WRONLY|O_CREAT|O_APPEND, 0666);
            dup2(fd, 1);

        }

        execvp(_argv[0], _argv);     
        //替换失败
        exit(44);
    }
    else if(id > 0)
    {
        int status = 0;
        pid_t ret = waitpid(id, &status, 0);
        if(ret == id)
        {
            last_code = WEXITSTATUS(status);
        }
    }
    else if(id < 0)
    {
        perror("fork");
        return;
    }
}

int builtCommand(int _argc, char* _argv[])
{
    if(_argc == 2 && strcmp("cd", _argv[0]) == 0)
    {
      chdir(_argv[1]);
      getpwd();
      sprintf(getenv("PWD"), "%s", pwd);
      //strcpy(getenv("PWD"), pwd);
      return 1;
    }
    else if(_argc == 2 && strcmp("echo", _argv[0]) == 0)
    {
        if(strcmp(_argv[1], "$?") == 0)
        {
            printf("%d\n", last_code);
            last_code = 0;
        }
        else if(*_argv[1] == '$')
        {
            char* val = getenv(_argv[1] + 1);
            if(val)  printf("%s\n", val);
        }
        else 
        {
            printf("%s\n", _argv[1]);
        }

        return 1;
    
    }
    else if(_argc == 2 && strcmp("export", _argv[0]) == 0)
    {
        strcpy(myenv, _argv[1]);
        putenv(myenv);
        return 1;
    }
    
    if(strcmp(_argv[0], "ls") == 0)
    {
        _argv[_argc++] = "--color";
        _argv[_argc] = NULL;
    }
    return 0;
}
int main()
{
    while(1)
    {

        rdir = NONE;
        filename = NULL;
        //2.交互问题,获取命令行
        interact(commandline, sizeof(commandline));
    
        //3.子串分割
        int argc = splitstring();
        
        //4.指令的判断
        int n = builtCommand(argc, _argv); 
        
        
        //5.普通命令的执行
        if(!n)  normalExecute();
    }
    return 0;
}
